package com.magicsoft.share.utils;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.magicsoft.share.bean.my.PayResult;
import com.magicsoft.share.bean.my.WxParameter;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

/**
 * @Author hwg
 * @Description：支付宝，微信支付工具类
 * @Date 2018/3/24
 */
public class PayUtil {

    private static PayUtil mPayUtil;

    /*************************支付宝支付所需参数*************************/
    private static final int SDK_PAY_FLAG = 1;
    //支付宝支付回调
    private AlipayCallBack mAlipayCallBack;


    /*************************微信支付所需参数*************************/
    private IWXAPI mIwxapi;


    public static PayUtil newInstance() {
        if (mPayUtil == null) {
            mPayUtil = new PayUtil();
        }
        return mPayUtil;
    }



    public void wechatPay(Context context, WxParameter wxParameter){
        mIwxapi = WXAPIFactory.createWXAPI(context, wxParameter.getAppId());

        if (!isWXAppInstalledAndSupported()) {
            ToastUtils.showToast(context, "您还未安装微信，请先安装微信");
            return;
        }

        PayReq req = new PayReq();
        req.appId = wxParameter.getAppId();
        req.partnerId = wxParameter.getPartnerId();
        req.prepayId = wxParameter.getPrepay_id();
        req.packageValue = wxParameter.getPackages() ;
        req.nonceStr = wxParameter.getNonceStr();
        req.timeStamp = wxParameter.getTimeStamp();
        req.sign = wxParameter.getPaySign();

        mIwxapi.sendReq(req);
    }

    /**
     * 判断微信客户端是否已经安装
     *
     * @return
     */
    private boolean isWXAppInstalledAndSupported() {

        boolean sIsWXAppInstalledAndSupported = mIwxapi.isWXAppInstalled()
                && mIwxapi.isWXAppSupportAPI();

        return sIsWXAppInstalledAndSupported;
    }



    /**
     * 支付宝支付
     */
    public void alipay(final Activity activity, final String alipayParam, AlipayCallBack alipayCallBack) {

        this.mAlipayCallBack = alipayCallBack ;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(alipayParam, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(payRunnable);
        authThread.start();
    }

    /**
     * 支付宝支付回调
     */
    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {

            switch (msg.what) {

                case SDK_PAY_FLAG:
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        if (mAlipayCallBack != null) {
                            mAlipayCallBack.paySuccess();
                        }
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        if (mAlipayCallBack != null) {
                            mAlipayCallBack.payFail();
                        }
                    }
                    break;
            }
        }
    };


    public interface AlipayCallBack {

        void paySuccess();

        void payFail();
    }

}
